package com.sayice.coursetable.logic.network;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 考试安排相关服务
 */
public abstract class ExamService {
    private static final String EXAM_URL = "http://jwgl.csuft.edu.cn/jsxsd/xsks/xsksap_list";

    /**
     * 获取考试安排页面（Jsoup Document）
     *
     * @param username 用户名
     * @param password 密码
     * @param term     学期
     * @return 返回 Jsoup 解析页面后得到的 Document对象，若获取失败则返回 null
     */
    public static Document getExamPage(String username, String password, String term) {
        String examHtml = LoginService.loginAndRequestHtml(username, password, httpClient -> {
            String html = null;
            FormBody requestBody = new FormBody.Builder()
                    .add("xqlbmc", "")
                    .add("xnxqid", term)
                    .add("xqlb", "")
                    .build();
            Request courseRequest = new Request.Builder()
                    .url(EXAM_URL)
                    .post(requestBody)
                    .build();
            try(Response examResponse = httpClient.newCall(courseRequest).execute()) {
                String body = Objects.requireNonNull(examResponse.body()).string();
                Elements examElements = Jsoup.parse(body).select(
                        "table[id=dataList]");
                if (examElements.size() != 0) {
                    html = examElements.get(0).outerHtml();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return html;
        });
        Log.d("ExamService", "examHtml: " + examHtml);
        return examHtml == null ? null : Jsoup.parseBodyFragment(examHtml);
    }
}
